import { login, getProfile, getUserDetailById } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import router from '@/router'
const state = {
  token: getToken() || '',
  profile: JSON.parse(localStorage.getItem('userName')) || {}
}

const mutations = {
  setToken(state, data) {
    // 存vuex
    state.token = data
    // 存本地
    setToken(data)
  },
  setUserInfo(state, data) {
    state.profile = data
    localStorage.setItem('userName', JSON.stringify(data))
  },

  removeToken(state) {
    state.token = ''
    removeToken()
  },
  removeProfile(state) {
    state.profile = {}
    localStorage.removeItem('userName')
  }
}

const actions = {
  async login(store, data) {
    const res = await login(data, store)
    // console.log("res  ----->  ", res);
    // 保存登录的时间戳---用于主动介入, 判断是否超时
    localStorage.setItem('loginTime', Date.now())
    // console.log('登录', res)
    store.commit('setToken', res.data.token)
    store.commit('setUserInfo', res.data.user_name)
  },
  // async getProfile(store, data) {
  //   const res = await getProfile()

  //   const detail = await getUserDetailById(res.userId)
  //   // console.log(3000, detail)

  //   store.commit('setProfile', {
  //     ...res,
  //     ...detail
  //   })
  // },
  logout(store) {
    store.commit('removeToken')
    store.commit('removeProfile')
    router.push('/login')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
